/**
 * Copyright (c) 2016-Now http://www.javamis.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 */
package com.javamis.modular.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javamis.common.message.Message;
import com.javamis.common.page.PageWarpper;
import com.javamis.modular.system.dao.DictDataMapper;
import com.javamis.modular.system.dao.RoleMapper;
import com.javamis.modular.system.entity.DictData;
import com.javamis.modular.system.entity.MenuTree;
import com.javamis.modular.system.entity.Role;
import com.javamis.modular.system.entity.RoleMenu;

/**
 * @name:   角色Controller层
 * @version:1.0.2
 * @author:	HuiJia
 * @QQ号： 	763236277
 * @QQ群： 	327773608
 * @邮箱: 	javamis@163.com
 * @site：	http://www.javamis.com
 */
@Controller
@RequestMapping("/role")
@SuppressWarnings("rawtypes")	//抑制单类型警告
public class RoleController {
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	DictDataMapper dictDataMapper;
    
    /**
     * 角色查询列表
     */
    @RequestMapping(value = "list",method = RequestMethod.GET)
    public String list(Model model) {
    	return "system/role/list";
    }
    
    @RequestMapping(value = "listData")
    @ResponseBody
    @SuppressWarnings("unlikely-arg-type")
    public PageWarpper<Role> listData(Role role){
    	PageWarpper<Role> pageWarpper = new PageWarpper<Role>();
    	IPage<Role> page = new Page<>(pageWarpper.getCurrentPage(), pageWarpper.getPageSize());//得到总页数
    	QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
    	String sortOrder =  pageWarpper.getSortOrder();
    	Map<String, Object> queryMap = role.setData(role);
		if(queryMap.isEmpty()) {
    		if(sortOrder.equals("desc")) {
    			queryWrapper.orderByDesc("code");
    		}if(sortOrder.equals("asc")) {
    			queryWrapper.orderByAsc("code");
    		}
    		roleMapper.selectPage(page, queryWrapper);
    	}if(!queryMap.isEmpty()) {
    		queryWrapper.allEq(queryMap);
    		roleMapper.selectPage(page, queryWrapper);
    	}
    	pageWarpper.setTotal(new Long(page.getTotal()).intValue());
    	List<Role> users = page.getRecords();
    	 
    	//从数据字典获取role_type类型，同时注入值到角色类型名称中
    	List<DictData> sexList = dictDataMapper.getDictDataByType("role_type");
    	Map<String,String> sexMap = new HashMap<String,String>();
 		for(DictData sex:sexList) {
 			sexMap.put(sex.getDictValue(), sex.getDictLabel());
 		}
 		List<Role> warpRoleTypeName = new ArrayList<Role>();
	   	for(Role use: users) {
	   		String setName = sexMap.get(use.getRoleType());
	   		use.setRoleTypeName(setName);
	   		warpRoleTypeName.add(use);
	   	}
    	pageWarpper.setRows(warpRoleTypeName);
    	return  pageWarpper;
    }
    
    
    /**
     * 角色表单页面
     * @param model
     * @return
     */
    @RequestMapping(value = "form")
    public String form() {
    	return "system/role/form";
    }
    
    /**
     * 添加角色
     */
    @RequestMapping("/save")
    @ResponseBody
    //@ExceptionHandler(RuntimeException.class)
    public Message save(@Valid Role role) {
    	role.setUpdateTime(new Date());
        this.roleMapper.insert(role);
        return Message.success();
    }
    
    /**
     * 根据角色id，修改角色信息
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value="edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
    	Role role = roleMapper.selectById(id);
    	model.addAttribute(role);
    	return "system/role/edit";
    }
    
    /**
     * 修改角色
     */
    @RequestMapping("/edit")
    @ResponseBody
    //@ExceptionHandler(RuntimeException.class)
    public Message edit(@Valid Role role, BindingResult result) {
    	role.setUpdateTime(new Date());
    	if(role.getParentName() == "") {role.setParentId(0);}
        this.roleMapper.updateById(role);
        return Message.success();
    }

    /**
     * 删除角色
     */
    //@ExceptionHandler(RuntimeException.class)
    @RequestMapping(value="delete")
    @ResponseBody
    public Object delete(@RequestParam Integer id) {
    	if(id == null) {
    		throw new RuntimeException("删除失败，出现异常");
    	}
        this.roleMapper.deleteById(id);
        return Message.success();
        //return new ErrorTip(405,"演示环境不能操作！");
    }
    
    /**
     * 角色表单页面
     * @param model
     * @return
     */
    @RequestMapping(value = "authority/{id}")
    public String authority(Model model,@PathVariable("id") int id) {
    	List<RoleMenu> rms= roleMapper.getMenusByRoleId(new RoleMenu(id));
    	String menuIds = "";
    	for(RoleMenu rm:rms) {
    		menuIds += ","+rm.getMenuid();
    	}
    	if(menuIds !="") {
    		menuIds = menuIds.substring(1);
    	}
    	model.addAttribute("id",id);
    	model.addAttribute("menuIds",menuIds);
    	return "system/role/authority";
    }
    
    
    /**
     * 查询角色树结构
	*/
	@RequestMapping(value = "tree/{curentIframeId}",method = RequestMethod.GET)
	public String tree(@PathVariable String curentIframeId,Model model) {
		if(curentIframeId !="undefined"&&!curentIframeId.equals("undefined") ) {
			model.addAttribute(curentIframeId);
		}
		return "system/role/roleTree";
	}
    
    /**
     * 为角色授权菜单
     */
    @RequestMapping(value="authorityMenu")
    @ResponseBody
    //@ExceptionHandler(RuntimeException.class)
    public Message authorityMenu(@RequestParam("menuIds") String menuIds, @RequestParam("id") int id) {
        String[] roleIds = menuIds.split(",");
        RoleMenu rm = new RoleMenu(id);
        roleMapper.deleteRoleMenuByRoleId(rm);
        for(int i=0;i<roleIds.length;i++) {
        	rm.setMenuid(Integer.valueOf(roleIds[i]));
        	roleMapper.insertRoleMenu(rm);
        }
        return Message.success();
    }
    
    @ResponseBody
   	@RequestMapping("/getRoleTree")
   	public List<Role> getRoleTree() {
   		List<Role> roleTreeList = roleMapper.getRoleTree();
   		return roleTreeList;
   	}
    
    @ResponseBody
	@RequestMapping("/getMenuTree")
	public List<MenuTree> getMenuTree() {
		List<MenuTree> roleTreeList = roleMapper.getMenuTree();
		return roleTreeList;
	}
}
